﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using MahApps.Metro.Controls;
using System.Collections.ObjectModel;
using MahApps.Metro.Controls.Dialogs;
using Aspose.Cells;
using System.Data.SQLite;

namespace LiteQueryWPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        FuncPanelHelper.ConfigLoader configLoader;

        public MainWindow()
        {
            InitializeComponent();
            InitPanels();
            txtInfo.Text = "当前版本: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            
        }

        private void InitPanels()
        {
            string cfgPath = AppDomain.CurrentDomain.BaseDirectory + "config.xml";
            configLoader = new FuncPanelHelper.ConfigLoader(cfgPath);
            if (configLoader == null)
            {
                this.ShowMessageAsync("错误", "配置文件初始化失败");
                return;
            }
            var cfg = configLoader.FuncConfig;
            if (cfg == null || cfg.Config == null)
            {
                this.ShowMessageAsync("错误", "配置文件config.xml没找到");
                return;
            }
            if (cfg.Config.AutoCreateDB)
            {
                cfg.Config.DataSource = string.Format(cfg.Config.DataSource, cfg.Config.DBName);
                if (!TestConnection())
                    return;
            }
            txtInfo.Text += " | 数据库: " + configLoader.FuncConfig.Config.DBName;
            if (cfg.Funcs.Count == 0)
                return;

            tabContent.Items.Clear();
            foreach (Entities.Func item in cfg.Funcs.OrderBy(x => x.Index))
            {
                AddTabPage(item, configLoader.FuncConfig.Config);
            }
        }

        bool AddTabPage(Entities.Func config, Entities.Config dbcfg)
        {
            try
            {
                // 创建面板容器
                var page = new TabItem() { Header= config.Name };
                // 添加数据面板
                var panel = new Controls.FuncPanel(config, dbcfg);
                page.Content=panel;
                tabContent.Items.Add(page);
                return true;
            }
            catch
            {
                return false;
            }
        }

        bool TestConnection()
        {
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection(configLoader.FuncConfig.Config.DataSource))
                {
                    conn.Open();
                    // 创建日志表
                    SqlFuncHelper.AsposeHelper.CreateLogDB(configLoader.FuncConfig.Config.DataSource);

                    conn.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            if (configLoader.FuncConfig == null || configLoader.FuncConfig.Config == null)
            {
                this.ShowMessageAsync("错误", "配置文件config.xml没找到");
                return;
            }
            var page = tabContent.SelectedItem;
            var tab = page as TabItem;
            var panel = tab.Content as Controls.FuncPanel;
            panel.Query();
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            var diag = Common.WinForm.SaveFileDialog();
            if (diag.Item1 == true)
            {
                var page = tabContent.SelectedItem;
                var tab = page as TabItem;
                var panel = tab.Content as Controls.FuncPanel;
                panel.Export(diag.Item2.FileName);
            }
        }

        private void mnuLoadOneExcel_Click(object sender, RoutedEventArgs e)
        {
            var diag = Common.WinForm.OpenFileDialog();
            if (diag.Item1 == true)
            {
                var ret = SqlFuncHelper.AsposeHelper.CreateAndInsert(configLoader.FuncConfig.Config.DataSource, configLoader.FuncConfig.Config.TableName, diag.Item2.FileName);
                if (ret.Item1)
                    this.ShowMessageAsync("提示","数据初始化成功");
                else
                    this.ShowMessageAsync("错误","数据初始化失败: " + ret.Item2.Message);
            }
        }

        private async void mnuLoadMulExcel_Click(object sender, RoutedEventArgs e)
        {
            var diag = Common.WinForm.OpenFileDialog();
            if (diag.Item1 == true)
            {
                var ret = SqlFuncHelper.AsposeHelper.CreateAndInsert(configLoader.FuncConfig.Config.DataSource, configLoader.FuncConfig.Config.TableName, diag.Item2.FileNames);
                var dial = DialogManager.GetCurrentDialogAsync<MessageDialog>(this).Result;
                if (ret.Item1)
                    await this.ShowMessageAsync("提示","数据初始化成功");
                else
                    await this.ShowMessageAsync("错误","数据初始化失败: " + ret.Item2.Message);

                System.Threading.Thread.Sleep(100);
               

                btnQuery_Click(null,null);
            }
        }

        private void mnuImportMulExcel_Click(object sender, RoutedEventArgs e)
        {
            var form = new ImportGuide();
            if (form.ShowDialog() == true)
            {
                var errList = new List<string>();
                foreach (LiteQueryWPF.Controls.FileRowPanel item in form.Rows)
                {
                    var ret = SqlFuncHelper.AsposeHelper.CreateAndInsert(configLoader.FuncConfig.Config.DataSource, item.TableName, item.FullFileName);
                    if (!ret.Item1)
                        errList.Add(item.FullFileName + " => " + ret.Item2.Message);
                }

                if (errList.Count == 0)
                    this.ShowMessageAsync("提示", "导入成功, 请参考配置模板[config.xml], 创建相应的查询面板.");
                else
                    this.ShowMessageAsync("错误", "导入失败\r\n" + string.Join("\r\n", errList.ToArray()));
            }
        }
    }
}
